package main

import (
	"basic-go/src/go-routine/util"
	"fmt"
	"time"
)

// 开启一个写数据协程，向管道写入50个整数
// 开启一个读数据协程，从管道读取整数
// 注意写数据和读数据协程操作的是同一个管道
// 主线程等待写数据和读数据协程都完成后才退出

var countDownLatch *util.CountDownLatch

func write(intChan chan int, count int) {
	for i := 1; i <= count; i++ {
		intChan <- i
		fmt.Println("write", i)
		time.Sleep(time.Second)
	}
	close(intChan)
	countDownLatch.CountDown()
}

func read(intChan chan int) {
	for res := range intChan {
		fmt.Println("read", res)
		time.Sleep(time.Second)
	}
	countDownLatch.CountDown()
}

func main() {

	var intChan chan int

	intChan = make(chan int, 10)

	countDownLatch = util.NewCountDownLatch(2)

	go write(intChan, 50)
	go read(intChan)

	countDownLatch.Await()

	fmt.Println("success")
}
